package com.yupi.quizai.scoring;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yupi.quizai.model.dto.question.QuestionContent;
import com.yupi.quizai.model.entity.App;
import com.yupi.quizai.model.entity.Question;
import com.yupi.quizai.model.entity.ScoringResult;
import com.yupi.quizai.model.entity.UserAnswer;
import com.yupi.quizai.model.vo.QuestionVO;
import com.yupi.quizai.service.QuestionService;
import com.yupi.quizai.service.ScoringResultService;

import javax.annotation.Resource;
import java.util.List;

@ScoringStrategyConfig(appType = 0, scoringStrategy = 0)
public class ScoringScoreStrategy implements ScoringStrategy{

    @Resource
    private QuestionService questionService;
    @Resource
    private ScoringResultService scoringResultService;

    @Override
    public UserAnswer doScore(List<String> choices, App app) {
        // 1. 根据id查询题目以及题目结果信息（从高到低排序）
        Question question = questionService.getOne(Wrappers.lambdaQuery(Question.class).eq(Question::getAppId, app.getId()));

        List<ScoringResult> scoringResults = scoringResultService.list(Wrappers.lambdaQuery(ScoringResult.class).eq(ScoringResult::getAppId, app.getId()).orderByDesc(ScoringResult::getResultScoreRange));


        // 2. 计算用户的总得分
        int totalScore = 0;
        QuestionVO questionVO = QuestionVO.objToVo(question);
        List<QuestionContent> questionContents = questionVO.getQuestionContent();

        for (int index = 0; index < questionContents.size(); index++) {
            QuestionContent questionContent = questionContents.get(index);
            String answer = choices.get(index);
            for (QuestionContent.Option option : questionContent.getOptions()) {
                if (option.getKey().equals(answer)) {
                    totalScore += option.getScore();
                    break;
                }
            }
        }
        // 3. 遍历得分结果 找到小于用户得分的最大值
        ScoringResult maxScoringResult = scoringResults.get(0);
        for (ScoringResult scoringResult : scoringResults) {
            if(totalScore > scoringResult.getResultScoreRange()){
                maxScoringResult = scoringResult;
                break;
            }
        }
        // 4. 返回结果
        UserAnswer userAnswer = new UserAnswer();
        userAnswer.setAppId(app.getId());
        userAnswer.setAppType(app.getAppType());
        userAnswer.setScoringStrategy(app.getScoringStrategy());
        userAnswer.setChoices(JSONUtil.toJsonStr(choices));
        userAnswer.setResultId(maxScoringResult.getId());
        userAnswer.setResultName(maxScoringResult.getResultName());
        userAnswer.setResultDesc(maxScoringResult.getResultDesc());
        userAnswer.setResultPicture(maxScoringResult.getResultPicture());
        userAnswer.setResultScore(totalScore);
        return userAnswer;
    }

}
